/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*
 * @State
 *
 * @Tags Jetstream2
 */
class Benchmark {
  public static void main(String[] args) throws Exception {
    runMandelbrot();
  }

  public static double mandelbrot() {
    int w = 1000;
    int h = w;
    int bit_num = 0;
    int i = 0;
    int byte_acc = 0;
    int iter = 50;
    double limit = 2.0;
    double Zr = 0;
    double Zi = 0;
    double Tr = 0;
    double Ti = 0;
    int res = 0;
    double limit2 = limit * limit;
    for (int y = 0; y < h; y++) {
      double Ci = 2.0 * y / h - 1.0;
      for (int x = 0; x < w; x++) {
        Zr = 0.0;
        Zi = 0.0;
        Tr = 0.0;
        Ti = 0.0;
        double Cr = 2.0 * x / w - 1.5;
        i = 0;
        while (i < iter && (Tr + Ti <= limit2)) {
          i += 1;
          Zi = 2.0 * Zr * Zi + Ci;
          Zr = Tr - Ti + Cr;
          Tr = Zr * Zr;
          Ti = Zi * Zi;
        }
        byte_acc <<= 1;
        if ((Tr + Ti) <= (limit2)) {
          byte_acc |= 0x01;
        }
        bit_num += 1;
        if (bit_num == 8) {
          res += byte_acc;
          byte_acc = 0;
          bit_num = 0;
        } else if (x == (w - 1)) {
          byte_acc <<= (8 - w % 8);
          res += byte_acc;
          byte_acc = 0;
          bit_num = 0;
        }
      }
    }
    return res;
  }

  public static void runMandelbrot() {
    double start = System.nanoTime();
    double res = mandelbrot();
    double end = System.nanoTime();
    double time = (double) (end - start) / 1000000;
    System.out.println("RunMandelbrot: "+res);
    System.out.println("Array Access - RunMandelbrot:\t" + time + "\tms");
  }
}
